<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="query.query.customerName" placeholder="请选择客户名称" clearable>
        <el-option v-for="item in partnersListData" :key="item.partnerCode" :label="item.partnerName"
          :value="item.partnerName">
        </el-option>
      </el-select>
      <!-- <el-input v-model="query.query.customerName" placeholder="请输入需求方名称" clearable @keyup.enter.native="search" /> -->
      <!-- <el-select v-model="query.query.customerMaterial" placeholder="请选择客户名称" clearable>
        <el-option v-for="item in partnersListData" :key="item.partnerCode" :label="item.partnerName"
          :value="item.partnerName">
        </el-option>
      </el-select> -->
      <!-- <el-input v-model="query.query.customerMaterial" placeholder="请选择购买商品名称" clearable @keyup.enter.native="search" /> -->
      <!-- <el-input v-model="query.query.materialName" placeholder="请输入对应我方物料名称" clearable @keyup.enter.native="search" /> -->
      <el-select v-model="query.query.materialName" placeholder="请输入对应我方物料名称" clearable>
        <el-option v-for="item in materialPageListData" :key="item.materialNo" :label="item.materialName"
          :value="item.materialName">
        </el-option>
      </el-select>
      <el-select v-model="query.query.demandState" placeholder="请选择需求状态" clearable>
        <el-option v-for="item in stateList" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-select v-model="query.query.sendGoodsState" placeholder="请选择发货状态" clearable>
        <el-option v-for="item in sendGoodsStateList" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-date-picker style="margin-left: 10px;" v-model="q_z_formDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
        type="daterange" range-separator="-" start-placeholder="需求开始日期" end-placeholder="需求结束日期"
        @change="q_z_selectTime" />
      <el-button type="primary" icon="el-icon-search" @click="handleClick(0)">查询</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="dialogVisible = true">新增</el-button>
      <el-button type="primary" icon="el-icon-upload2" @click="handleClick(1)">上传</el-button>
      <el-button type="primary" icon="el-icon-sort" @click="handleClick(2)">转为需求</el-button>
      <el-button type="primary" icon="el-icon-check" @click="handleClick(3)">预收提交</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="handleClick(4)">生成发货数据</el-button>
      <el-button type="primary" icon="el-icon-folder" @click="handleClick(5)">订单合同</el-button>
      <el-button @click="handleExport" type="primary" icon="el-icon-download">
        {{ $t("table.export") }}
      </el-button>
    </div>
    <el-table :data="tableData" style="width: 100%;margin-bottom: 20px;" row-key="id" highlight-current-row border
      @selection-change="handleSelectionChange" :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }" @cell-click="cellClick">
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column prop="customerOrderNo" label="客户订单号" width="160" />
      <el-table-column prop="salesOrderNumber" label="销售订单号" width="160" />
      <el-table-column prop="customerName" label="客户名称" width="160" />
      <el-table-column prop="customerMaterial" label="购买商品名称" width="130" />
      <el-table-column prop="materialName" label="对应我方物料名称" width="160" />
      <el-table-column prop="materialNo" label="对应我方物料代码" width="160" />
      <el-table-column prop="sendGoodsDate" label="需求日期" width="120">
        <template slot-scope="{ row: { sendGoodsDate,diffDayToDemandDate } }">
          <span
            :style="{ color: diffDayToDemandDate <= 10 && diffDayToDemandDate > 5 ? 'darkorange' : diffDayToDemandDate <= 5 ? 'red' : '' }">{{
              getMoment(sendGoodsDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="orderGoodsNum" label="订单数量" />
      <el-table-column prop="unitTaxedPrice" label="单价（含税）" width="130" />
      <el-table-column prop="receivableAmount" label="应收金额（含税）" width="140" />
      <el-table-column prop="inAdvanceAmount" label="预收金额">
        <!-- <template slot-scope="{row}">
          <span v-if="!row.isHandle">{{ row.inAdvanceAmount }}</span>
          <div v-else>
            <el-input size="small" placeholder="请输入预收金额" v-model="row.advanceCollectAmount">
              <el-button @click="handleAdvanceCollectAmount(0, row)" size="small" type="primary" slot="prepend"
                icon="el-icon-close"></el-button>
              <el-button @click="handleAdvanceCollectAmount(1, row)" size="small" type="primary" slot="append"
                icon="el-icon-check"></el-button>
            </el-input>
          </div>
        </template> -->
      </el-table-column>
      <el-table-column prop="paymentMethod" label="收款方式" />
      <el-table-column prop="invoiceDate" label="收款日期" />
      <el-table-column prop="totalAmount" label="收款金额" />
      <el-table-column prop="invoiceCode" label="开票状态">
        <template slot-scope="{row:{invoiceCode,invoiceDate,invoiceData}}">
          <el-popover placement="top" width="400" trigger="hover" :disabled="!invoiceData || !invoiceData.length">
            <el-table :data="invoiceData">
              <el-table-column width="200" property="invoiceCode" label="发票号"></el-table-column>
              <el-table-column width="200" property="invoiceDate" label="开票日期"></el-table-column>
            </el-table>
            <div slot="reference">{{ invoiceData && invoiceData.length ? '已开票' : '未开票' }}</div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="frequency" label="需求状态" width="100">
        <template slot-scope="{ row: { demandState } }">
          <el-tag :type="demandState == 0 ? 'danger' : 'success'">{{ demandState == 0 ? "未" : "已" }}转需求</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="outStoreGoodsNum" label="已发货数量" width="100" />
      <el-table-column prop="sendGoodsState" label="发货状态" width="100">
        <template slot-scope="{ row: { sendGoodsState } }">
          {{ getSendGoodsState(sendGoodsState) }}
        </template>
      </el-table-column>
      <el-table-column width="400" :label="$t('table.actions')" align="center">
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleDetail(row.salesOrderNumber)">详情</el-button>
          <el-button size="mini" type="primary" @click="handleUpdate(row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="closeOrder(row.id)" :disabled="row.state == '2'">关闭</el-button>
          <el-button size="mini" type="danger" :disabled="!row.inAdvanceAmount"
            @click="cancelYs(row.id)">取消预收</el-button>
          <el-button size="mini" type="danger" :disabled="row.demandState != '0'" @click="handleDelete(row)">{{
            $t("table.delete") }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="query.pageIndex" :limit.sync="query.pageSize"
      @pagination="getInfo" />
    <el-dialog width="40%" :close-on-click-modal="false" :visible.sync="detailDialogVisible" title="详细">
      <el-table :data="detailData" row-key="id" highlight-current-row border
        :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }" ref="multipleTable">
        <el-table-column prop="changeTime" label="销售单时间">
          <template slot-scope="{ row }">
            <span>{{ row.changeTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="changeNum" label="销售单数量" />
      </el-table>
    </el-dialog>
    <el-dialog :title="form.id ? '编辑' : '新增'" :visible.sync="dialogVisible" @closed="handleClose"
      :close-on-click-modal="false">
      <el-form ref="ruleForm" :model="form" :rules="rules">
        <el-row v-if="form.demandState != '1'">
          <el-col :span="12">
            <el-form-item label="客户订单号" prop="customerOrderNo" :label-width="formLabelWidth">
              <el-input v-model="form.customerOrderNo" autocomplete="off" placeholder="请输入客户订单号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName" :label-width="formLabelWidth">
              <el-select style="width:100%" v-model="form.customerId" filterable placeholder="请选择客户名称">
                <el-option v-show="item.state == 1" v-for="item in partnersListData" :key="item.id"
                  :label="item.partnerName" :value="item.id">
                </el-option>
              </el-select>
              <!-- <el-select style="width:100%" v-model="form.customerId" placeholder="请选择需求方" clearable>
                <el-option v-for="item in partnersListData" :key="item.id" :label="item.partnerName" :value="item.id">
                </el-option>
              </el-select> -->
              <!-- <el-input v-model="form.customerName" autocomplete="off" placeholder="请输入需求方名称" clearable></el-input> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.demandState != '1'">
          <el-col :span="12">
            <el-form-item label="购买商品名称" prop="customerMaterial" :label-width="formLabelWidth">
              <el-input v-model="form.customerMaterial" autocomplete="off" placeholder="请输入客户物料" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="对应我方物料名称" prop="materialName" :label-width="formLabelWidth">
              <el-select style="width: 100%;" filterable v-model="form.myMaterialId" placeholder="请选择对应我方物料代码" clearable
                @change="handleMyMaterial">
                <el-option v-show="item.state == 1" v-for="item in materialPageListData" :key="item.id"
                  :label="item.materialName" :value="item.id">
                </el-option>
              </el-select>
              <!-- <el-input v-model="form.materialName" autocomplete="off" placeholder="请输入我方物料" clearable></el-input> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.demandState != '1'">
          <el-col :span="12">
            <el-form-item label="对应我方物料代码" prop="materialNo" :label-width="formLabelWidth">
              <el-input v-model="form.materialNo" autocomplete="off" :disabled="true" placeholder="请输入我方物料" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求日期" prop="sendGoodsDate" :label-width="formLabelWidth">
              <el-date-picker style="width: 100%;" v-model="form.sendGoodsDate" type="date" placeholder="请选择发货日期"
                clearable></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.demandState != '1'">
          <el-col :span="12">
            <el-form-item label="订单数量" prop="orderGoodsNum" :label-width="formLabelWidth">
              <!-- 
                onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')"
            
            -->
              <el-input v-model="form.orderGoodsNum" autocomplete="off" @input="handleOrderGoodsNum"
                placeholder="请输入订单数量" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税率" prop="taxRate" :label-width="formLabelWidth">
              <el-input v-model="form.taxRate" autocomplete="off" placeholder="请输入税率" clearable :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.demandState != '1'">
            <el-form-item label="单价（含税）" prop="unitTaxedPrice" :label-width="formLabelWidth">
              <el-input v-model="form.unitTaxedPrice" autocomplete="off"
                onkeyup="value = value.match(/\d+(\.\d{0,4})?/)[0] || ''" @input="handleUnitTaxedPrice"
                placeholder="请输入单价（含税）" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价（不含税）" prop="unitPrice" :label-width="formLabelWidth">
              <el-input v-model="form.unitPrice" autocomplete="off"
                onkeyup="value = value.match(/\d+(\.\d{0,4})?/)[0] || ''" @input="handleUnitPrice"
                placeholder="请输入单价（不含税）" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="应收金额" prop="receivableAmount" :label-width="formLabelWidth">
              <el-input v-model="form.receivableAmount" autocomplete="off"
                onkeyup="value=value.replace(/[^\-?\d.]/g,'')" placeholder="请输入应收金额" clearable :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" :label-width="formLabelWidth">
              <el-input v-model="form.remark" autocomplete="off" placeholder="请输入备注" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="warehouseNameTableData" style="width: 100%;margin-bottom: 20px;" row-key="id"
        highlight-current-row border @selection-change="handleSelectionChange"
        :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
        @cell-click="cellClick">
        <el-table-column prop="warehouseName" label="仓库" />
        <el-table-column prop="stockNum" label="库存数量" />
      </el-table>
      <el-table v-if="form.id" :data="form.addressList" row-key="id" highlight-current-row border
        :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
        <el-table-column prop="partnerName" label="客户名称">
          <template slot-scope="{ row, $index }">
            <el-input v-model="row.partnerName" placeholder="请输入客户名称" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="telephone" label="手机号">
          <template slot-scope="{ row, $index }">
            <el-input v-model="row.telephone" placeholder="请输入手机号" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="contact" label="联系人">
          <template slot-scope="{ row, $index }">
            <el-input v-model="row.contact" placeholder="请输入联系人" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址">
          <template slot-scope="{ row, $index }">
            <el-input v-model="row.address" placeholder="请输入地址" clearable />
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="
          form = {};
        dialogVisible = false;
        ">取 消</el-button>
        <el-button type="primary" @click="sure">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="批量导入订单" width="400px" :visible.sync="importExportVisible" @closed="importHandleClose"
      :close-on-click-modal="false">
      <div>
        <el-button type="text" @click="downloadExcel">下载模版</el-button>
        <el-upload ref="elUpload" drag :auto-upload="false" action="#" :limit="1" :on-change="handleChange"
          :on-remove="handleRemove">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importExportVisible = false">取 消</el-button>
        <el-button type="primary" @click="importExportSure">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="订单合同" :visible.sync="orderVisible" @closed="orderHandleClose" width="500px"
      :close-on-click-modal="false">
      <el-form ref="orderRuleForm" :model="orderForm" :rules="orderRules">
        <el-row>
          <el-col :span="24">
            <el-form-item label="开户行" prop="bankName" label-width="70px">
              <el-select style="width:100%" v-model="orderForm.bankId" placeholder="请选择开户行" clearable
                @change="handleBank">
                <el-option v-for="item in orderList" :key="item.id" :label="`${item.bankName}/${item.bankAccount}`"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="合同类型" prop="downloadMode">
              <el-radio-group v-model="orderForm.downloadMode">
                <el-radio label="EXCEL">excel</el-radio>
                <el-radio label="PDF">pdf</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="银行账号" prop="bankAccount" label-width="100px">
              <el-select style="width:100%" v-model="orderForm.bankAccount" :disabled="true" placeholder="请选择银行账号" clearable>
                <el-option v-for="item in orderList" :key="item.id" :label="item.bankAccount" :value="item.bankAccount">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orderVisible = false">取 消</el-button>
        <el-button type="primary" @click="orderSure">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog @closed="fundHandleClose" width="70%" :close-on-click-modal="false" :visible.sync="fundDialogVisible"
      title="预收">
      <el-button style="margin-bottom:10px" type="primary" icon="el-icon-plus" @click="handleBind">
        绑定
      </el-button>
      <el-table :data="fundTableData" row-key="id" highlight-current-row border @selection-change="handleSelectionBind"
        :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }" ref="multipleTable">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="subjectType" label="收入/支出" />
        <el-table-column prop="subjectName" label="科目" />
        <el-table-column prop="price" label="金额" />
        <el-table-column prop="priceCopy" label="使用金额">
          <template slot-scope="{row}">
            <el-input v-model.trim="row.priceCopy" onkeyup="value=value.replace(/[^\d.]/g,'')" placeholder="请输入使用金额"
              clearable />
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="creator" />
        <el-table-column label="创建时间" prop="createTime" width="160">
          <template slot-scope="{ row }">
            <span>{{ new Date(row.createTime) | parseTime() }}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- <el-form ref="fundRuleForm" :model="fund" label-width="140px" :rules="fundRules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="资金账号" prop="accountId">
              <el-select style="width: 100%;" v-model="fund.accountId" clearable placeholder="请选择资金账号" filterable>
                <el-option v-for="item in orderList" :key="item.id" :label="`${item.bankName}/${item.bankAccount}`"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用预收金额" prop="prePrice">
              <el-input v-model.trim="fund.prePrice" placeholder="请输入核销金额" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="金额（含税）" prop="totalAmount">
              <el-input :disabled="true" v-model.trim="fund.totalAmount" placeholder="请输入金额（含税）" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form> -->
      <!-- <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="fundDialogVisible = false">{{ $t('permission.cancel') }}</el-button>
        <el-button type="primary" @click="fundConfirm">{{ $t('permission.save') }}</el-button>
      </div> -->
    </el-dialog>
    <el-dialog @closed="sendHandleClose" width="60%" :close-on-click-modal="false" :visible.sync="sendDialogVisible"
      title="发货信息">
      <el-form ref="sendRuleForm" :model="sendForm" :rules="sendRules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="出库单号" prop="outStoreNo" label-width="100px">
              <el-input v-model="sendForm.outStoreNo" size="small" placeholder="请输入入库单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库数量" prop="outStoreNum" label-width="100px">
              <el-input v-model="sendForm.outStoreNum" placeholder="请输入出库数量" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="送货地址" prop="addressId" label-width="100px">
              <el-select style="width:100%" v-model="sendForm.addressId" placeholder="请选择送货地址" clearable>
                <el-option v-for="item in addressList" :key="item.id" :label="item.address" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sendDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  orderPageList,
  orderOutStoreApply,
  orderAdvanceCollectSubmit,
  orderChangeToDemand,
  orderDel,
  orderAdd,
  orderModify,
  importOrder,
  orderGeneralBargain,
  accGetYsYf,
  accBindYsYf,
  accGetYsYfValue,
  accCancelYsYf,
  wmsStockWarehouseList,
  smSellOrderCloseOrder,
  smSellOrderExportExcel,
  codePartnersAddress,
  accSellStatementCount
} from "@/api/andonProblemLevel";
import { stockPageList } from '@/api/qmsQualityManagement'
import { accountGetAll } from "@/api/product";
import { accAddReceive } from "@/api/evaluatePerformance";
import { partnersList } from "@/api/andonProblemManager";
import { materialPageList } from "@/api/departentment";
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { deepClone, arraryRemove, downfile, downloadFile } from "@/utils";
import moment from "moment";
import { downLoadTemplate } from "../../../utils";
import math from "@/utils/math";
import Decimal from "@/utils/decimal.js"

export default {
  name: "AndonProblemLevel",
  components: { Pagination },
  directives: { waves },
  data() {
    var validatePass = (rule, value, callback) => {
      const reg = /^[1-9]\d*$/
      if (!value) {
        callback(new Error('请输入出库数量'));
      } else if (!reg.test(value)) {
        callback(new Error('出库数量必须为正整数'));
      } else {
        callback();
      }
    };
    return {
      detailData: [],
      detailDialogVisible: false,
      sendGoodsStateList: [{
        label: '未发货',
        value: 0
      }, {
        label: '部分发货',
        value: 1
      }, {
        label: '发货完成',
        value: 2
      }],
      sendRules: {
        // outStoreNo: [
        //   { required: true, message: "请输入出库单号", trigger: "blur" }
        // ],
        outStoreNum: [
          { required: true,validator: validatePass, trigger: 'blur' }
        ],
        addressId: [
          { required: true, message: "请选择送货地址", trigger: "change" }
        ],
      },
      sendForm: {},
      addressList: [],
      sendDialogVisible: false,
      importExportForm: {},
      importExportVisible: false,
      stateList: [
        {
          label: "未转需求",
          value: 0
        },
        {
          label: "已转需求",
          value: 1
        }
      ],
      dialogVisible: false,
      total: 0,
      q_z_formDate: [],
      query: {
        pageIndex: 1,
        pageSize: 20,
        query: {
          demandState: null
        }
      },
      tableData: [],
      selectedList: [],
      selectedListData: [],
      formLabelWidth: "140px",
      form: {
        receivableAmount: 0,
        unitPrice: '',
        customerMaterial: ''
      },
      rules: {
        customerOrderNo: [
          { required: true, message: "请输入客户订单号", trigger: "blur" }
        ],
        customerName: [
          { required: true, message: "请输入需求方名称", trigger: "blur" }
        ],
        customerMaterial: [
          { required: true, message: "请输入需求物料名称", trigger: "blur" }
        ],
        materialName: [
          { required: true, message: "请输入对应我方物料名称", trigger: "blur" }
        ],
        sendGoodsDate: [
          { required: true, message: "请选择发货日期", trigger: "blur" }
        ],
        orderGoodsNum: [
          { required: true, message: "请输入订单数量", trigger: "blur" }
        ],
        receivableAmount: [
          { required: true, message: "请输入应收金额", trigger: "blur" }
        ],
        unitPrice: [
          { required: true, message: "请输入单价（不含税）", trigger: "blur" }
        ],
        unitTaxedPrice: [
          { required: true, message: "请输入单价（含税）", trigger: "blur" }
        ],
        materialNo: [
          { required: true, message: "请输入对应我方物料代码", trigger: "blur" }
        ]
      },
      partnersListData: [],
      materialPageListData: [],
      orderVisible: false,
      orderRules: {
        bankName: [
          { required: true, message: "请选择开户行", trigger: "change" }
        ],
        bankAccount: [
          { required: true, message: "请选择银行账号", trigger: "change" }
        ],
        templateId: [
          { required: true, message: "请选择合同模版", trigger: "change" }
        ],
        downloadMode: [
          { required: true, message: "请选择合同文件类型", trigger: "change" }
        ]
      },
      orderList: [],
      orderForm: {
        downloadMode: 'EXCEL'
      },
      fundDialogVisible: false,
      fund: {},
      fundRules: {
        accountId: [
          { required: true, message: "请选择资金账户", trigger: "change" }
        ],
        prePrice: [
          { required: true, message: "请输入核销金额", trigger: "blur" }
        ]
      },
      fundTableData: [],
      warehouseNameTableData: []
    };
  },
  mounted() {
    this.getInfo();
    this.getPartnersList();
    this.getMaterialPageList();
    this.getAccountGetAll();
  },

  methods: {
    async handleDetail(salesOrderNumber) {
      const { records } = await stockPageList({
        pageSize: 10,
        pageIndex: 1,
        query: {
          orderNo: salesOrderNumber
        }
      })
      this.detailData = records
      this.detailDialogVisible = true
      // this.generateId = id
      // this.generateTableData = await wmsStoreApplyBatchNumberList(id)
      // this.generateDialogVisible = true
    },
    sendSure() {
      this.$refs["sendRuleForm"].validate(async valid => {
        if (valid) {
          try {
            const { outStoreNum, addressId, outStoreNo } = this.sendForm
            await orderOutStoreApply(this.selectedList[0], outStoreNum, addressId, outStoreNo);
            this.getInfo();
            this.$message.success("操作成功！");
            this.sendDialogVisible = false
          } catch (err) {
            // downfile("发货单.xlsx", err)
          }
        }
      })
    },
    sendHandleClose() {
      this.sendForm = {};
      this.$refs["sendRuleForm"].resetFields();
    },
    async handleExport() {
      try {
        const { query } = this.query
        await smSellOrderExportExcel(
          query
        )
      } catch (err) {
        const reader = new FileReader();
        reader.readAsText(err);
        reader.onload = (event) => {
          const resultString = reader.result; // 这里就是转换后的字符串
          if (resultString.includes('code') && resultString.includes('isSuccess')) {
            this.$message.error(JSON.parse(resultString).message)
          } else {
            downfile('销售订单.xlsx', err);
          }
        }
      }
    },
    getSendGoodsState(val) {
      if (val == '0') {
        return "未发货";
      } else if (val == '1') {
        return "部分发货";
      } else if (val == '2') {
        return "关闭";
      }
    },
    async closeOrder(id) {
      this.$confirm("此操作将关闭当前订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await smSellOrderCloseOrder(id)
        this.getInfo();
        this.$message.success("操作成功！");
      })
    },
    async cancelYs(id) {
      this.$confirm("此操作将取消预收, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        const formData = new FormData();
        formData.append("sellOrderId", id);
        const params = new URLSearchParams(formData);
        await accCancelYsYf(params);
        this.getInfo();
        this.$message.success("操作成功！");
      });
    },
    async handleBind() {
      if (this.selectedListBind.length > 1) {
        this.$message.warning("只能选择一条订单");
        return;
      } else if (!this.selectedListBind.length) {
        this.$message.warning("请至少选择一条订单");
        return;
      }
      const find = this.fundTableData.find(type => type.id == this.selectedListBind[0])
      if (Number(find.priceCopy) > Number(find.price) || Number(find.priceCopy) <= 0) {
        this.$message.error('使用金额区间为大于0并且小于金额，请重新输入！')
        return
      }
      const formData = new FormData();
      formData.append("id", this.selectedListBind[0]);
      formData.append("price", find.priceCopy)
      formData.append("sellOrderId", this.selectedList[0]);
      const params = new URLSearchParams(formData);
      await accBindYsYf(params);
      this.getInfo();
      this.$message.success("操作成功！");
      this.fundDialogVisible = false;
    },
    orderHandleClose() {
      this.orderForm = {
        downloadMode: 'EXCEL'
      };
      this.$refs["orderRuleForm"].resetFields();
    },
    handleBank(val) {
      if (val) {
        const find = this.orderList.find(type => type.id == val);
        this.orderForm.bankAccount = find.bankAccount;
        this.orderForm.bankName = find.bankName;
      } else {
        this.orderForm = {};
      }
    },
    fundConfirm() {
      this.$refs["fundRuleForm"].validate(async valid => {
        if (valid) {
          const { accountId, prePrice, idStr } = this.fund;
          await accAddReceive({
            accountId: accountId,
            price: prePrice,
            smOrderId: idStr
          });
          this.$message.success("操作成功！");
          this.fundDialogVisible = false;
        }
      });
    },
    async getAccountGetAll() {
      this.orderList = await accountGetAll();
    },
    fundHandleClose() {
      this.fund = {};
      this.$refs["fundRuleForm"].resetFields();
    },
    querySearch(queryString, cb) {
      let restaurants = this.partnersListData;
      let results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.partnerName
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    orderSure() {
      const arr = this.selectedListData.map(type => type.customerId)
      const s = new Set(arr)
      if (s.size > 1) {
        this.$message.error("非同一个客户,不能生成!")
        return
      }
      this.$refs["orderRuleForm"].validate(async valid => {
        if (valid) {
          try {
            await orderGeneralBargain({
              ...this.orderForm,
              id: this.selectedList.join(',')
            });
          } catch (err) {
            const reader = new FileReader();
            reader.readAsText(err);
            reader.onload = (event) => {
              const resultString = reader.result; // 这里就是转换后的字符串
              if (resultString.includes('code') && resultString.includes('isSuccess')) {
                this.$message.error(JSON.parse(resultString).message)
              } else {
                const name = this.orderForm.downloadMode === 'PDF' ? '订单合同.pdf' : '订单合同.xlsx'
                downfile(name, err);
                this.orderVisible = false;
              }
            }
          }
        }
      });
    },
    async handleAdvanceCollectAmount(type, item) {
      if (type) {
        await orderAdvanceCollectSubmit(
          item.idStr,
          item.advanceCollectAmount,
          0
        );
        this.$message.success("操作成功！");
        this.getInfo();
      }
      item.isHandle = false;
    },
    cellClick(row, column, cell, event) {
      return;
      if (column.property === "inAdvanceAmount") {
        this.$set(row, "advanceCollectAmount", row.inAdvanceAmount);
        this.$set(row, "isHandle", true);
      }
    },
    async importExportSure() {
      try {
        if (!this.importExportForm.file) {
          this.$message.warning("请先上传商品数据");
          return false;
        }
        const formData = new FormData();
        for (let key in this.importExportForm) {
          formData.append(key, this.importExportForm[key]);
        }
        await importOrder(formData);
        this.getInfo();
        this.$message.success("导入成功");
        this.importExportVisible = false;
      } catch (err) {
        this.handleRemove();
        this.$refs["elUpload"].clearFiles();
      }
    },
    handleChange(file, fileList) {
      this.importExportForm.file = file.raw;
    },
    handleRemove() {
      this.importExportForm.file = "";
    },
    downloadExcel() {
      downLoadTemplate("销售订单模板.xlsx", "销售订单模板.xlsx");
    },
    importHandleClose() {
      this.$refs["elUpload"].clearFiles();
    },
    // handleOrderGoodsNum(num) {
    //   if (num) {
    //     this.form.receivableAmount = math.multiply(
    //       num,
    //       this.form.unitTaxedPrice
    //     );
    //   } else {
    //     this.form.receivableAmount = "";
    //   }
    // },

    handleOrderGoodsNum(value) {
      // 使用正则表达式过滤非数字字符
      const num = value.replace(/^(0+)|[^\d]+/g, "");

      // 检查过滤后的值是否为空或无效数字
      if (!num || isNaN(parseFloat(num))) {
        this.form.orderGoodsNum = ""; // 清空输入框内容
        return; // 终止后续操作
      }

      // 更新表单数据
      this.form.orderGoodsNum = num;

      // 检查 unitTaxedPrice 是否有值
      if (
        this.form.unitTaxedPrice === undefined ||
        this.form.unitTaxedPrice === null ||
        isNaN(parseFloat(this.form.unitTaxedPrice))
      ) {
        console.warn("unitTaxedPrice 没有值或无效");
        return; // 终止后续操作
      }

      // 计算应收金额
      this.form.receivableAmount = parseFloat(num) * this.form.unitTaxedPrice;
    },

    handleUnitTaxedPrice(num) {
      if (num) {
        this.form.receivableAmount = math.multiply(
          num,
          this.form.orderGoodsNum
        );
        if (this.form.taxRate) {
          let a = new Decimal(this.form.taxRate)
          let b = new Decimal(100)
          let c = new Decimal(1)
          let d = new Decimal(num)
          let e = d.div(c.plus(a.div(b)))
          this.form.unitPrice = Number(e.toFixed(2))
        }
      } else {
        this.form.receivableAmount = "";
        this.form.unitPrice = ''
      }
    },
    handleUnitPrice(num) {
      if (num && this.form.taxRate) {
        let a = new Decimal(this.form.taxRate)
        let b = new Decimal(100)
        let c = new Decimal(1)
        let d = new Decimal(num)
        let e = d.times(c.plus(a.div(b)))
        this.form.unitTaxedPrice = Number(e.toFixed(2))
        this.form.receivableAmount = math.multiply(
          this.form.unitTaxedPrice,
          this.form.orderGoodsNum
        );
      } else {
        this.form.receivableAmount = "";
        this.form.unitTaxedPrice = ''
      }
    },
    // handleMyMaterial(id) {
    //   if (id) {
    //     const item = this.materialPageListData.find(type => type.id == id);
    //     this.form.unitPrice = item.untaxedUnitPrice;
    //     this.form.unitTaxedPrice = item.includingTaxPrice;
    //     this.form.materialNo = item.materialNo;
    //   } else {
    //     this.form.unitPrice = this.form.unitTaxedPrice = this.form.receivableAmount = this.form.materialNo =
    //       "";
    //   }
    // },
    async handleMyMaterial(id) {
      if (id) {
        const item = this.materialPageListData.find(type => type.id == id);
        this.$set(this.form, 'unitPrice', item.untaxedUnitPrice)
        this.$set(this.form, 'unitTaxedPrice', item.includingTaxPrice)
        this.$set(this.form, 'materialNo', item.materialNo)
        this.$set(this.form, 'taxRate', item.taxRate)
        this.form.customerMaterial = this.materialPageListData.find(type => type.id == id).materialName

        if (
          !isNaN(this.form.orderGoodsNum) &&
          !isNaN(this.form.unitTaxedPrice)
        ) {
          this.form.receivableAmount =
            parseFloat(this.form.orderGoodsNum) * this.form.unitTaxedPrice;
        } else {
          this.form.receivableAmount = "";
        }
        this.warehouseNameTableData = await wmsStockWarehouseList(id)
      } else {
        this.form.unitPrice = this.form.unitTaxedPrice = this.form.receivableAmount = this.form.materialNo =
          "";
        this.warehouseNameTableData = []
        this.form.customerMaterial = ''
      }
    },
    handleClose() {
      this.warehouseNameTableData = []
      this.form = {};
      this.$refs["ruleForm"].resetFields();
    },
    getPartnersList() {
      partnersList({
        pageIndex: 1,
        pageSize: 10000,
        query: {
          partnerType: 1
        }
      }).then(res => {
        const { records } = res;
        this.partnersListData = records;
      });
    },
    getMaterialPageList() {
      materialPageList({
        pageIndex: 1,
        pageSize: 1000
      }).then(res => {
        const { records } = res;
        this.materialPageListData = records;
      });
    },
    q_z_selectTime(val = []) {
      val = val || [];
      const { query } = this.query;
      query.planBeginDate = val[0] || "";
      query.planEndDate = val[1] || "";
    },
    async sure() {
      const httpFn = this.form.id ? orderModify : orderAdd;
      await httpFn(this.form);
      this.getInfo();
      this.$message.success("操作成功");
      this.dialogVisible = false;
    },
    async handleClick(type) {
      switch (type) {
        case 0:
          this.query.pageIndex = 1;
          this.getInfo();
          break;
        case 1:
          this.importExportVisible = true;
          break;
        case 2:
          if (!this.selectedList.length) {
            this.$message.warning("请至少选择一条订单");
            return;
          }
          await orderChangeToDemand(this.selectedList.join(","));
          this.$router.push({
            path: "/procure/demand"
          });
          this.$message.success("操作成功");
          break;
        case 3:
        case 4:
          if (this.selectedList.length > 1) {
            this.$message.warning("只能选择一条订单");
            return;
          } else if (!this.selectedList.length) {
            this.$message.warning("请至少选择一条订单");
            return;
          }
          if (type == 3) {
            if (this.selectedListData[0].inAdvanceAmount) {
              this.$message.warning("该订单已提交过预收，不能重复提交！");
              return;
            }
            const formData = new FormData();
            formData.append("partnerId", this.selectedListData[0].customerId);
            formData.append("subjectName", "预收");
            const params = new URLSearchParams(formData);
            this.fundTableData = await accGetYsYf(params);
            this.fundTableData.forEach(item => {
              this.$set(item, 'priceCopy', item.price)
            })
            // this.fund = this.selectedListData[0]
            // this.$set(this.fund, 'prePrice', 0)
            // this.fund.prePrice = 0
            this.fundDialogVisible = true;
            // await orderAdvanceCollectSubmit(this.selectedList[0], this.selectedListData[0].inAdvanceAmount, this.selectedListData[0].inAdvanceGoodsNum)
            // this.$message.success('操作成功')
          } else if (type == 4) {
            if (this.selectedListData[0].sendGoodsState == '2') {
              this.$message.warning('已关闭订单不能生成发货数据！')
              return
            }
            this.addressList = await codePartnersAddress(this.selectedListData[0].customerId)
            this.sendDialogVisible = true
            // this.$prompt("请输入出库数量", "提示", {
            //   confirmButtonText: "确定",
            //   cancelButtonText: "取消",
            //   inputPattern: /^[1-9]\d*$/,
            //   inputErrorMessage: "出库数量必须为正整数"
            // }).then(async ({ value }) => {
            //   try {
            //     await orderOutStoreApply(this.selectedList[0], value);
            //     this.getInfo();
            //     this.$message("操作成功！");
            //   } catch (err) {
            //     // downfile("发货单.xlsx", err)
            //   }
            // });
          }
          break;
        case 5:
          if (!this.selectedList.length) {
            this.$message.warning("请至少选择一条订单");
            return;
          }
          this.orderVisible = true;
          break;
        default:
          break;
      }
    },
    handleSelectionChange(e) {
      this.selectedList = [];
      this.selectedListData = [];
      e.forEach(item => {
        this.selectedList.push(item.idStr);
        this.selectedListData.push(item);
      });
    },
    handleSelectionBind(e) {
      this.selectedListBind = [];
      e.forEach(item => {
        this.selectedListBind.push(item.id);
      });
    },
    getMoment(day) {
      return moment(day).format("YYYY-MM-DD");
    },
    async getInfo() {
      const { records, total } = await orderPageList(this.query);
      let ids = []
      records.forEach(item => {
        ids.push(item.id)
      })
      const data = await accSellStatementCount(ids.join(','))
      records.forEach(item => {
        for (let key in data) {
          if (item.id == key) {
            item.totalAmount = data[key].totalAmount;
            item.invoiceDate = data[key].invoiceDate;
            item.paymentMethod = data[key].paymentMethod;
            item.invoiceCode = data[key].invoiceCode;
            item.invoiceData = data[key].invoiceData;
          }
        }
      })
      this.tableData = records;
      this.total = total;
      // if (records.length) {
      //   const sellOrderIds = records.map(item => item.idStr).join(",");
      //   const formData = new FormData();
      //   formData.append("sellOrderIds", sellOrderIds);
      //   const params = new URLSearchParams(formData);
      //   const data = await accGetYsYfValue(params);
      //   data.forEach(item => {
      //     try {
      //       records.forEach(i => {
      //         if (item.sellOrderId === i.idStr) {
      //           this.$set(i, "inAdvanceAmount", item.price);
      //           throw new Error();
      //         }
      //       });
      //     } catch (err) { }
      //   });
      // }
    },
    search() {
      this.query.pageIndex = 1;
      this.getInfo();
    },
    async handleUpdate(row) {
      this.form = deepClone(row);
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm("确认删除?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await orderDel(row.idStr);
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          arraryRemove(this.tableData, row);
        })
        .catch(err => console.error(err));
    }
  }
};
</script>
